﻿using System;
using System.Net;
using System.Windows;
using System.Linq;
using SMS.Entities.BaseClasses;
using SMS.Entities;
using System.Windows.Data;
using System.Collections.Generic;
using SMS.Common.Silverlight;
using SMS.Model;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows.Controls;

namespace SMS.ViewModel.Master
{
    public class CustomerMasterViewModel : BaseNotify
    {
        CustomerModel _model;

        public CustomerMasterViewModel()
        {
            SearchCommand = new DelegateCommand(Search_Click);
            SaveCommand = new DelegateCommand(Save_Click);
            NewCommand = new DelegateCommand(New_Click);
            LoadTransactionCommand = new DelegateCommand(Loadtransaction_Click);
            ShowDetailCommand = new DelegateCommand(ShowDetailCommand_Click);
            ReceiveCommand = new DelegateCommand(ReceiveCommand_Clicked);

            if (!DesignerProperties.IsInDesignTool)
            {
                _model = new CustomerModel();
                _model.OnServiceError += new Action<SMSException>(_model_OnServiceError);
                _model.OnSaveCompleted += new Action<int>(_model_OnSaveCompleted);
                _model.OnSearchCompleted += new Action<System.Collections.ObjectModel.ObservableCollection<Customer>>(_model_OnSearchCompleted);
                _model.OnGetCustomerTransactionCompleted += new Action<System.Collections.ObjectModel.ObservableCollection<CustomerTransaction>>(_model_OnGetCustomerTransactionCompleted);
                _model.OnSaveCustomerTransactionCompleted += new Action<int>(_model_OnSaveCustomerTransactionCompleted);
            }
        }

        void _model_OnSaveCustomerTransactionCompleted(int obj)
        {
            var tempTransaction = new CustomerTransaction();
            tempTransaction.TransactionDate = DateTime.Now;
            tempTransaction.IsLive = true;
            tempTransaction.CreditDebit = Entities.Enums.TransactionType.Credit;
            tempTransaction.Customer = SelectedMaster;
            tempTransaction.SaleHistory = TransactionList.LastOrDefault().SaleHistory;
            tempTransaction.SalesMan = App.CurrentSalesMan;
            tempTransaction.Transaction_Id = obj;
            tempTransaction.Amount = ReceiveAmount;
            TransactionList.Add(tempTransaction);
            UserMessage = "Transaction saved successfully.";
            ReceiveAmount = 0;
        }

        void _model_OnGetCustomerTransactionCompleted(System.Collections.ObjectModel.ObservableCollection<CustomerTransaction> obj)
        {
            decimal debit = 0;
            decimal credit = 0;
            foreach (var item in obj)
            {
                if (item.CreditDebit == Entities.Enums.TransactionType.Credit)
                    credit += item.Amount;
                else
                    debit += item.Amount;
                item.RunningTotal = debit - credit;
            }
            TransactionList = obj;
            TotalDebit = debit;
            TotalCredit = credit;
            Balance = TotalDebit - TotalCredit;
            UserMessage = "Customer transaction loaded.";
        }

        void _model_OnSearchCompleted(System.Collections.ObjectModel.ObservableCollection<Customer> obj)
        {
            UserMessage = obj.Count + " customers found";
            CustomerList = new List<Customer>(obj);
            PagedCustomerList = new PagedCollectionView(CustomerList);
        }

        void _model_OnSaveCompleted(int obj)
        {
            UserMessage = "Customer saved successfully.";
            SelectedMaster.Customer_ID = obj;
        }

        void _model_OnServiceError(SMSException obj)
        {
            ErrorMessage = obj.Message;
        }

        private List<Customer> _CustomerList;

        public List<Customer> CustomerList
        {
            get { return _CustomerList; }
            set { _CustomerList = value; OnPropertyChanged("CustomerList"); }
        }

        private Customer _SelectedMaster;

        public Customer SelectedMaster
        {
            get { return _SelectedMaster; }
            set { _SelectedMaster = value; OnPropertyChanged("SelectedMaster"); TransactionList = null; }
        }

        private PagedCollectionView _PagedCustomerList;

        public PagedCollectionView PagedCustomerList
        {
            get { return _PagedCustomerList; }
            set { _PagedCustomerList = value; OnPropertyChanged("PagedCustomerList"); }
        }

        private string _SearchText;

        public string SearchText
        {
            get { return _SearchText; }
            set { _SearchText = value; OnPropertyChanged("SearchText"); }
        }


        public ICommand SearchCommand { get; private set; }

        public void Search_Click(object param)
        {
            _model.SearchCustomer(SearchText);

            UserMessage = "Searching customer...";
        }

        public ICommand SaveCommand { get; private set; }


        public void Save_Click(object param)
        {
            if (SelectedMaster != null)
            {
                _model.SaveCustomer(SelectedMaster);

                UserMessage = "Saving customer...";
            }
            else
            {
                ErrorMessage = "No Customer to save";
            }
        }

        public ICommand NewCommand { get; private set; }

        public void New_Click(object param)
        {
            if (CustomerList == null)
                CustomerList = new List<Customer>();
            var k = new Customer() { IsLive = true };
            CustomerList.Add(k);
            PagedCustomerList = new PagedCollectionView(CustomerList);
            PagedCustomerList.MoveToLastPage();
            SelectedMaster = k;
        }

        #region CustomerTransaction Related

        private DateTime? _SelectedFromDate;

        public DateTime? SelectedFromDate
        {
            get { return _SelectedFromDate; }
            set { _SelectedFromDate = value; OnPropertyChanged("SelectedFromDate"); }
        }

        private DateTime? _ToDate;

        public DateTime? SelectedToDate
        {
            get { return _ToDate; }
            set { _ToDate = value; OnPropertyChanged("SelectedToDate"); }
        }



        public ICommand LoadTransactionCommand { get; private set; }
        public void Loadtransaction_Click(object param)
        {
            if (SelectedMaster != null)
            {
                if (!SelectedFromDate.HasValue)
                    SelectedFromDate = DateTime.Now.AddDays(-DateTime.Now.DayOfYear);
                if (!SelectedToDate.HasValue)
                    SelectedToDate = DateTime.Now.AddDays(1);
                _model.GetCustomerTransactionList(SelectedMaster.Customer_ID, SelectedFromDate.Value, SelectedToDate.Value);
                TransactionList = null;
                if (Convert.ToString(param) == string.Empty)
                {
                    ChildWindow chilwindow = new ChildWindow() { Opacity = .95, Height = App.AppDimension.Height * .9, Width = App.AppDimension.Width * .9 };
                    chilwindow.Content = new Views.Master.CustomerTransactionHistory() { DataContext = this };
                    chilwindow.Show();
                }
                UserMessage = "Loading customer transactions...";
            }
            else
            {
                ErrorMessage = "No customer selected to load transaction";
            }
        }

        private System.Collections.ObjectModel.ObservableCollection<CustomerTransaction> _TransactionList;

        public System.Collections.ObjectModel.ObservableCollection<CustomerTransaction> TransactionList
        {
            get { return _TransactionList; }
            set { _TransactionList = value; OnPropertyChanged("TransactionList"); }
        }

        public ICommand ShowDetailCommand { get; private set; }
        public void ShowDetailCommand_Click(object param)
        {
            var transaction = param as CustomerTransaction;
            if (transaction != null)
            {
                ///Code to show detail here......
            }
        }

        private decimal _ReceiveAmount;

        public decimal ReceiveAmount
        {
            get { return _ReceiveAmount; }
            set { _ReceiveAmount = value; OnPropertyChanged("ReceiveAmount"); }
        }

        private decimal _TotalDebit;

        public decimal TotalDebit
        {
            get { return _TotalDebit; }
            set { _TotalDebit = value; OnPropertyChanged("TotalDebit"); }
        }

        private decimal _TotalCredit;

        public decimal TotalCredit
        {
            get { return _TotalCredit; }
            set { _TotalCredit = value; OnPropertyChanged("TotalCredit"); }
        }

        private decimal _Balance;

        public decimal Balance
        {
            get { return _Balance; }
            set { _Balance = value; OnPropertyChanged("Balance"); }
        }





        public ICommand ReceiveCommand { get; private set; }
        private CustomerTransaction _newTransaction;
        public void ReceiveCommand_Clicked(object param)
        {
            if (ReceiveAmount > 0)
            {
                if (TransactionList != null)
                {
                    _newTransaction = new CustomerTransaction();
                    _newTransaction.TransactionDate = DateTime.Now;
                    _newTransaction.IsLive = true;
                    _newTransaction.CreditDebit = Entities.Enums.TransactionType.Credit;
                    _newTransaction.Customer = SelectedMaster;
                    _newTransaction.SaleHistory = TransactionList.LastOrDefault().SaleHistory;
                    _newTransaction.SalesMan = App.CurrentSalesMan;
                    _newTransaction.Amount = ReceiveAmount;
                    _model.SaveCustomerTransaction(_newTransaction);
                    UserMessage = "Saving new transaction...";
                }
                else
                {
                    ErrorMessage = "Please load transaction first!";
                }
            }
            else
            {
                ErrorMessage = "Amount should be greater than 0";
            }
        }


        #endregion
    }
}
